package com.p7.framework.permission.shiro.filter;

import java.io.PrintWriter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 登录过滤器
 * @ClassName: ClientAuthenticationFilter 
 * @author p7+
 * @date 2019年2月25日 下午9:43:21 
 * @Copyright:
 */
public class ClientAuthenticationFilter extends AccessControlFilter {

    /**
     * 是否允许访问；mappedValue 就是[urls]配置中拦截器参数部分，如果允许访问返回 true，否则 false
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        Subject subject = getSubject(request, response);
        return subject.isAuthenticated();
    }

    /**
     * isAccessAllowed 返回 false 时，执行该方法
     * @param request
     * @param response
     * @return 返回 true 表示需要其他filter或者其他代码逻辑继续处理；返回 false 表示该拦截器实例已经处理，随后该会话结束
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {

        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");
        PrintWriter out = httpServletResponse.getWriter();

        ObjectMapper mapper = new ObjectMapper();
        out.write(mapper.writeValueAsString("登录已失效"));
        out.flush();
        out.close();

        return false;
    }
}
